<template>
	<view class="container flex-c">
		<uni-nav-bar class="ch-nav" height="88rpx" backgroundColor="#ffffff" leftWidth="90rpx" rightWidth="90rpx" color="#333" :fixed="true" :padding="false" :border="false" @clickLeft="$goBack(1)">
			<template slot="left">
				<image class="left" src="@/public/images/public/dhl_fhjt.png" mode="aspectFit"></image>
			</template>
			<text class="title">个人资料</text>
		</uni-nav-bar>
		<view class="body flex-c">
			<view class="list">
				<view class="list-item image flex-r ac">
					<view class="item-title">
						头像
					</view>
					<view class="item-right flex-r" @tap="chooseImage">
						<lazy-image class="avatar" :src="user.avatar+'?imageView2/1/w/120/h/120/q/50'" type="user" fit="cover"></lazy-image>
						<uni-icons type="right" color="#999999" size="38rpx"></uni-icons>
					</view>
				</view>
			</view>
			<view class="list">
				<view class="list-item flex-r ac">
					<view class="item-title">
						昵称
					</view>
					<view class="item-right flex-r" @tap="editNickName">
						<text class="status">{{user.nickname}}</text>
						<uni-icons type="right" color="#999999" size="38rpx"></uni-icons>
					</view>
				</view>
				<view class="list-item flex-r ac">
					<view class="item-title">
						性别
					</view>
					<view class="item-right flex-r">
						<picker @change="sexChange" :range="sexs" :value="user.sex">
							<view class="input">
								<text class="status">{{sexs[sexIndex]}}</text>
								<uni-icons type="right" color="#999999" size="38rpx"></uni-icons>
							</view>
						</picker>
					</view>
				</view>
				<view class="list-item flex-r ac">
					<view class="item-title">
						生日
					</view>
					<view class="item-right flex-r">
						<picker @change="dateChange" :value="user.brithday && user.brithday.substr(0, 10)" mode="date" :start="startDate" :end="endDate">
							<view class="input">
								<text class="status" v-if="date">{{date}}</text>
								<text class="status" v-else-if="user.brithday">{{user.brithday.substr(0, 10)}}</text>
								<text class="status" v-else>请设置生日</text>
								<uni-icons type="right" color="#999999" size="38rpx"></uni-icons>
							</view>
						</picker>
					</view>
				</view>
			</view>
		</view>
		<view class="cropper-wrap" v-if="cropperImg">
			<view class="cropper-wrap-tools">
				<view class="cropper-wraper-cancel" @click="cancelCropper">取消</view>
				<view class="cropper-wraper-confirm" @click="confirmCorpper">确定</view>
			</view>
			<image-cropper
				cutWidth="200px"
				id="image-cropper"
				:zoom="1"
				:angle="0"
				:keepRatio="true"
				:showCtrlBorder='true'
				:disableRotate='true'
				:imageCenter="true"
				:disableCtrl="true"
				fileType="jpg"
				:src="cropperImg"
				@load="cropperLoaded"
				@cropped="cropped"
			  />
		</view>
		<uni-popup ref="message" type="message">
			<uni-popup-message :type="msgType" :message="messageText" :duration="2000"></uni-popup-message>
		</uni-popup>
		<uni-popup ref="popup" type="dialog">
			<uni-popup-dialog mode="input" title="修改昵称" placeholder="请输入新的昵称" @confirm="nameConfirm"></uni-popup-dialog>
		</uni-popup>
	</view>
</template>

<script>
	import imMsg from "@/utils/common/message.js";
	import * as qiniu from 'qiniu-js'
	export default {
		data() {
			return {
				msgType: 'success',
				messageText: '',
				sexs: ['女','男'],
				sexIndex: null,
				date: null,
				avatarImage: null,
				cropperImg: null,
				croppedImg: null,
				domainUrl: null,
			}
		},
		components: {
			ImageCropper: () => import('./components/nice-cropper/cropper.vue')
		},
		computed: {
			user() {
				return this.$store.state.user
			},
			startDate() {
				return this.getDate('start')
			},
			endDate() {
				return this.getDate('end')
			}
		},
		onLoad() {
			this.sexIndex = this.user.sex
		},
		methods: {
			//用户选择上传图片
			chooseImage(){
				uni.chooseImage({
					count: 1,
					sizeType: ['compressed'],
					extension: ['jpg','png'],
					success: (res) => {
						console.log(res.tempFilePaths[0]);
						this.cropperImg = res.tempFilePaths[0];
					}
				});
			},
			//图片加载完成触发
			cropperLoaded(image){
				this.croppedImg = image.path
			},
			//每次操作裁剪触发
			cropped(imagePath, imageInfo) {
				console.log(imageInfo);
				this.croppedImg = imagePath
			},
			//取消裁剪
			cancelCropper(){
				this.cropperImg = ''
				this.croppedImg = ''
			},
			//确认完成裁剪
			confirmCorpper(){
				this.cropperImg = ''
				this.avatarImage = this.croppedImg
				this.croppedImg = ''
				this.$ShowLoading({show: true})
				this.uploadAvatar()
			},
			//上传图片
			uploadAvatar(){
				this.$http.post({
					url: '/api/getToken',
				}).then(data => {
					console.log(data);
					if(data.success && data.result){
						this.domainUrl = data.result.url
						this.token = data.result.token
						let file = this.base64ConvertFile(this.avatarImage)
						this.avatarImage = ''
						//七牛上传请求
						this.qiniuUpload(file).then((res)=>{
							console.log(res);
							this.avatarImage = this.domainUrl + '/' + res.key
							let userInfoModel = {
								avatar: this.avatarImage
							}
							this.editUserInfo(userInfoModel)
						}).catch((err)=>{
							console.log(err);
							uni.showToast({
								title: '头像上传失败，请重试',
								icon: 'none'
							})
						}).finally(()=>{
							this.$ShowLoading({show: false})
						})
					}else{
						this.$ShowLoading({show: false})
						uni.showToast({
							title: data.message || '头像上传失败，请稍后重试',
							icon: 'none'
						})
					}
				}).catch((err) => {
					console.log(err);
					this.$ShowLoading({show: false})
					uni.showToast({
						title: '头像上传失败，请稍后重试',
						icon: 'none'
					})
				})
			},
			//七牛上传图片
			qiniuUpload(file) {
				return new Promise((resolve,reject)=>{
					let type = file.type.substr(6)
					let key = Date.now() + 'H5.' + type
					const observer = {
						next(res){
							console.log(res);
						},
						error(err){
							console.log(err);
							reject(err)
						},
						complete(res){
							console.log(res);
							resolve(res)
						}
					}
					const options = {
						quality: 0.4,
						noCompressIfLarger: true
					}
					//压缩图片
					qiniu.compressImage(file, options).then(data => {
						const observable = qiniu.upload(data.dist, key, this.token)
						const subscription = observable.subscribe(observer) // 上传开始
					})
				})
			},
			//修改用户基础信息
			editUserInfo(userInfoModel) {
				this.$http.post({
					url: '/api/appUser/editUserInfo',
					data: {
						userId: this.user.userId,
						...userInfoModel
					},
				}).then(data => {
					console.log(data);
					if(data.success){
						uni.showToast({
							title: '修改成功！',
							icon: 'success'
						})
						//请求用户最新信息
						this.$store.commit('UPDATE_USERINFO', userInfoModel)
						setTimeout(()=>{
							//更新IM用户资料
							if(this.$store.state.imReady){
								imMsg.updateMyProfile()
							}
						}, 1500)
					}else{
						console.log(data);
						uni.showToast({
							title: data.message,
							icon: 'none'
						})
					}
				}).catch((err) => {
					console.log(err);
					uni.showToast({
						title: '请求错误，请稍后重试',
						icon: 'none'
					})
				})
			},
			//修改昵称
			editNickName() {
				//this.$refs.popup.open()
				this.$goByName('editnickname')
			},
			//昵称修改确认
			nameConfirm(value) {
				console.log(value);
				if(value){
					if(value.length < 2 || value.length > 5){
						this.messageToggle('error', '请输入2-5位长度的昵称')
						return false;
					}
					if(value == this.user.nickname){
						this.messageToggle('error', '新昵称和原昵称不能相同')
						return false;
					}
					this.submitEditName(value);
					this.$refs.popup.close();
				}else{
					this.messageToggle('error', '请输入新的昵称')
				}
			},
			//提交修改昵称
			submitEditName(name){
				console.log(name);
				let userInfoModel = {
					nickname: name
				}
				this.editUserInfo(userInfoModel)
			},
			//消息提示
			messageToggle(type, msg) {
				this.msgType = type
				this.messageText = msg
				this.$refs.message.open()
			},
			//自定义底部菜单
			showActionSheet(){
				uni.showActionSheet({
					itemList: ['女','男'],
					success: (res) => {
						if(res.tapIndex == 0){
							
						}
						if(res.tapIndex == 1){
							
						}
					}
				});
			},
			//选择性别
			sexChange(e){
				console.log(e.detail.value)
				this.sexIndex = e.detail.value
				let userInfoModel = {
					sex: this.sexIndex
				}
				this.editUserInfo(userInfoModel)
			},
			//选择生日
			dateChange(e) {
				console.log(e.detail.value)
				this.date = e.detail.value
				if(this.date + ' 00:00:00' != this.user.brithday){
					let userInfoModel = {
						brithday: this.date + ' 00:00:00'
					}
					this.editUserInfo(userInfoModel)
				}
			},
			//获取日期
			getDate(type) {
				const date = new Date();
				let year = date.getFullYear();
				let month = date.getMonth() + 1;
				let day = date.getDate();
	
				if (type === 'start') {
					year = year - 60;
				} else if (type === 'end') {
					year = year - 10;
				}
				month = month > 9 ? month : '0' + month;
				day = day > 9 ? day : '0' + day;
				return `${year}-${month}-${day}`;
			},
			base64ConvertFile(urlData) { // 64转file
				var arr = urlData.split(',')
				var type = arr[0].match(/:(.*?);/)[1]
				var fileExt = type.split('/')[1]
				var bstr = atob(arr[1])
				var n = bstr.length
				var u8arr = new Uint8Array(n)
				while (n--) {
					u8arr[n] = bstr.charCodeAt(n);
				}
				return new File([u8arr], Date.now() + 'H5.' + fileExt, {
					type: type
				});
			}
		}
	}
</script>

<style lang="scss" scoped>
	.container{
		min-height: var(--safe-height);
	}
	.body{
		margin-top: 20rpx;
		.list{
			margin-bottom: 20rpx;
			background-color: #FFFFFF;
			.list-item{
				height: 96rpx;
				padding: 0 20rpx;
				box-sizing: border-box;
				border-bottom: 1rpx solid #EDEDED;
				.item-title{
					line-height: 30rpx;
					font-size: 30rpx;
					font-weight: 400;
					flex: 2;
				}
				.item-right{
					align-items: center;
					.avatar{
						width: 96rpx;
						height: 96rpx;
						border-radius: 50%;
						background-color: #FFFFFF;
						background-size: 100%;
						margin-right: 15rpx;
					}
					.input{
						display: flex;
						align-items: center;
					}
					.status{
						font-size: 28rpx;
						color: #999999;
						line-height: 28rpx;
						margin-right: 15rpx;
					}
					.uni-icons{
						//line-height: 40rpx;
					}
				}
				&.image{
					height: 120rpx;
				}
			}
			.list-item:last-child{
				border: none;
			}
		}
	}
	.cropper-wrap {
		position: fixed;
		top: 0;
		left: 0;
		right: 0;
		height: calc(100vh - var(--vh-offset, 0px) - var(--safe-area-inset-bottom));
		z-index: 6;
		background-color: rgba(0, 0, 0, 1);
		.cropper-wrap-tools {
			position: absolute;
			left: 0;
			top: 156rpx;
			width: 100%;
			display: flex;
			justify-content: space-between;
			z-index: 66;
			.cropper-wraper-cancel , .cropper-wraper-confirm {
				width: 250rpx;
				height: 88rpx;
				display: flex;
				justify-content: center;
				align-items: center;
				color: #FFFFFF;
				font-size: 32rpx;
			}
		}
	}
</style>
